package com.google.code.lightsomy.output;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.code.lightsomy.errors.ApplicationException;
import com.google.code.lightsomy.http.LightsomyConstants;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;

/**
 * Renderer implementation for FreeMarker template engine.
 * 
 * @author Viktoras Agejevas
 *
 */
public class FreeMarkerRenderer extends LightsomyRenderer {
	
	private Map<String, Object> parameters;
	
	private Configuration cfg;
	
	FreeMarkerRenderer(final HttpServletRequest request, final HttpServletResponse response) {
		super(request, response, Type.FREE_MARKER);

		parameters = new HashMap<String, Object>();
		String path = request.getSession().getServletContext().getRealPath("/");
		
    	try {
    		cfg = new Configuration();
			cfg.setDirectoryForTemplateLoading(new File(path));
			cfg.setObjectWrapper(new DefaultObjectWrapper());
		} catch (IOException e) {
			throw new ApplicationException("Wrong templates path", e);
		}
        set("root", 
        		request.getParameter(
        				LightsomyConstants.LIGHTSOMY_ROOT_URL.getValue()));
        set("resources", 
        		request.getParameter(
        				LightsomyConstants.LIGHTSOMY_RESOURCES_ROOT_URL.getValue()));
	}
	
	@Override
	protected String process(String page) {	
        try {
	        Template temp = cfg.getTemplate(page);
	        Writer out = new StringWriter();
	        temp.process(parameters, out);
	        return out.toString();
		} catch (Exception e) {
			throw new ApplicationException("Failed to render a page", e);
		}
	}

	@Override
	public void set(String key, Object value) {
		parameters.put(key, value);
	}
	
	@Override
	public Object get(String key) {
		return parameters.get(key);
	}
}
